#include "client.h"

int enter(int sockfd){
    FANHUI:
    printf("*************************\n"
            "   登录界面\n"
            
            "   选项0：登录\n"
            "   选项1：注册\n"
            "   请输入选项："
            );
    fflush(stdout);
    int opt;
    scanf("%d", &opt);
    //printf("user opt = %d\n", opt);

    if(opt == 0){
        send(sockfd, &opt, sizeof(opt), MSG_NOSIGNAL);
        return login(sockfd);
    }else if(opt == 1){
        send(sockfd, &opt, sizeof(opt), MSG_NOSIGNAL);
        return regis(sockfd);
    }else{
        goto FANHUI;
    }
}

int regis(int sockfd){
    printf("*************************\n"
            "   请输入要注册的用户名：");
    fflush(stdout);
    char username[1024] = {0};
    scanf("%s", &username);
    printf("   请输入要注册的密  码：");
    fflush(stdout);
    char password[1024] = {0};
    scanf("%s", &password);

    char buf[1024] = {0};
    sprintf(buf, "%s/%s", username, password);
    //发送用户信息
    train_t train;
    bzero(&train, sizeof(train));
    train.dataLength = strlen(buf);
    strcpy(train.data, buf);
    send(sockfd, &train, sizeof(int) + train.dataLength, MSG_NOSIGNAL);

    //接收成功或失败信息
    int isSuc;
    recv(sockfd, &isSuc, sizeof(isSuc), 0);
    if(isSuc == 1){
        printf("   注册成功！\n");
        send(sockfd, &isSuc, sizeof(isSuc), MSG_NOSIGNAL);
        login(sockfd);
    }else{
        printf("   注册失败：用户名重复\n");
        return 0;
    }

}

int login(int sockfd){
    printf("*************************\n"
            "   请输入用户名：");
    fflush(stdout);
    char username[1024] = {0};
    scanf("%s", &username);
    printf("   请输入密  码：");
    fflush(stdout);
    char password[1024] = {0};
    scanf("%s", &password);

    char buf[1024] = {0};
    sprintf(buf, "%s/%s", username, password);
    //printf("userinfo = %s\n", buf);

    //发送用户名/密码
    train_t train;
    bzero(&train, sizeof(train));
    train.dataLength = strlen(buf);
    strcpy(train.data, buf);
    send(sockfd, &train, sizeof(int) + train.dataLength, MSG_NOSIGNAL);
    int isSuc;
    recv(sockfd, &isSuc, sizeof(isSuc), 0);
    if(isSuc == 1){
        printf("*************************\n"
                "   欢迎进入网盘！\n"
                "   %s:~/pan/%s$ ", username, username);
        fflush(stdout);
    }else if(isSuc == 0){
        printf("*************************\n"
                "   密码输入错误！\n");
        return 0;
    }
    //int ret = send(netfd ,)

    return 1;
}
